package com.leadingsoft.pwxk.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

import javax.management.RuntimeErrorException;

import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class FileUtil {

	private static String path;

	@Value("${file.path}")
	public void setPath(String path) {
		FileUtil.path = path;
	}

	/**
	 * 
	 * @param in
	 *            文件输入流
	 * @param fileName
	 *            文件原名称
	 * @return 服务器上文件名称，用于下载文件
	 */
	public static String saveFile(InputStream in, String fileName) {
		log.info("进入文件拷贝业务：" + fileName);
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddhhmmss");
		LocalDateTime ldt = LocalDateTime.now();

		FileOutputStream out;
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdir();
		}
		int lastIndexOf = fileName.lastIndexOf(".");
		if (lastIndexOf == -1) {
			log.info("获取文件后缀名失败，未保存文件");
			return null;
		}
		String suffix = fileName.substring(lastIndexOf, fileName.length());
		String newName = UUID.randomUUID().toString().replace("-", "") + dtf.format(ldt) + suffix;
		File file = new File(dir, newName);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				log.error("复制文件服务异常：" + e.getMessage(), e);
			}
		}
		try {
			out = new FileOutputStream(file);
			// 该方法内部已经关闭文件流
			Long len = Streams.copy(in, out, true);
			log.info("文件大小：" + len);
			return newName;
		} catch (IOException e) {
			log.error("复制文件服务异常：" + e.getMessage(), e);
			throw new RuntimeErrorException(null, "复制文件服务异常");
		}
	}

}
